#include "clock.h"
#include <time.h>
#ifndef _MSC_VER
#include <sys/time.h>
#else
#define WIN32_LEAN_AND_MEAN
#include <winsock2.h>
#endif

namespace common
{
#ifdef _MSC_VER
	int gettimeofdayex(struct timeval *tp, void *tzp)
	{
		time_t clock;
		struct tm tm;
		SYSTEMTIME wtm;
		GetLocalTime(&wtm);
		tm.tm_year = wtm.wYear - 1900;
		tm.tm_mon = wtm.wMonth - 1;
		tm.tm_mday = wtm.wDay;
		tm.tm_hour = wtm.wHour;
		tm.tm_min = wtm.wMinute;
		tm.tm_sec = wtm.wSecond;
		tm.tm_isdst = -1;
		clock = mktime(&tm);
		tp->tv_sec = clock;
		tp->tv_usec = wtm.wMilliseconds * 1000;
		return (0);
	}
#endif

	uint64_t Clock::NowUSecond( )
	{
		timeval tv;
#ifdef _MSC_VER
		::common::gettimeofdayex(&tv, 0);
#else
		gettimeofday(&tv, 0);
#endif
		return 1000000LL * tv.tv_sec + tv.tv_usec;
	}

	Clock::Clock( ) :
		start_( 0 ),
		elapsed_( 0 ),
		active_( false )
	{
	}

	Clock::~Clock( )
	{
	}

	int32_t Clock::elapsed( ) const
	{
		if ( active( ) == false )
		{
			return elapsed_;
		}
		return  static_cast< int32_t >( NowUSecond( ) - start_ );
	}

	int32_t Clock::Start( )
	{
		active_ = true;
		start_ = NowUSecond( );
		return start_;
	}

	int32_t Clock::Stop( )
	{
		elapsed_ = elapsed( );
		active_ = false;
		return elapsed_;
	}

}
